<template>
    <div>
        <!-- 头部：新增 + 搜索 -->
        <el-row style="margin: 10px">
            <el-col :span="12">
        <span>
        <el-button type="primary" @click="showNewInfo()">新增客户端</el-button>
      </span>
            </el-col>
            <el-col :span="12">
        <span style="float: right">
          <el-input style="width: 200px" v-model="query" placeholder="输入搜索内容"/>
          <el-button type="primary" style="margin-left: 10px" @click="queryClient()">搜索</el-button>
        </span>
            </el-col>
        </el-row>
        <!-- 中间：列表 + 修改 + 删除 -->
        <el-row>
            <el-table :data="clientList" border style="width: 100%;margin-left: 5px;margin-right: 5px">
                <el-table-column prop="client_id" label="客户端ID"/>
                <el-table-column prop="client_secret" label="客户端密钥"/>
                <el-table-column prop="client_name" label="客户端名称"/>
                <el-table-column prop="authorization_grant_types" :show-overflow-tooltip='true' label="授权模式"/>
                <el-table-column prop="redirect_uris" :show-overflow-tooltip='true' label="重定向url"/>
                <el-table-column prop="scopes" :show-overflow-tooltip='true' label="权限范围"/>
                <el-table-column prop="authorization_code_expires" label="code过期时间"/>
                <el-table-column prop="access_token_expires" label="token过期时间"/>
                <el-table-column prop="refresh_token_expires" label="刷新token时间"/>
                <el-table-column fixed="right" label="操作" width="100">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="showEditInfo(scope.row)">修改</el-button>
                        <el-button link type="primary" size="small" @click="deleteInfo(scope.row.client_id)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-row>

        <!-- 分页 -->
        <el-row :justify="'center'" style="margin-top: 10px">
            <el-pagination
                    :current-page=currentPage
                    :total=totalPage
                    @current-change="currentChange"
                    layout="prev, pager, next"
            />

        </el-row>

        <!-- 模态 -->
        <el-dialog
                v-model="showModel"
                title="用户信息"
                width="30%"
        >
            <el-form :model="clientInfo" label-width="120px">
                <el-form-item label="客户端名称">
                    <el-input v-model="clientInfo.client_name"/>
                </el-form-item>
                <el-form-item label="客户端密钥">
                    <el-input v-model="clientInfo.client_secret"/>
                </el-form-item>
                <el-form-item label="授权模式">
                    <el-checkbox-group v-model="clientInfo.authorization_grant_types">
                        <el-checkbox v-for="agt in authorizationGrantTypes" :label="agt"/>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="权限范围">
                    <el-checkbox-group v-model="clientInfo.scopes">
                        <el-checkbox v-for="sc in scopeTag" :key="sc.tag" :label="sc.permission">{{
                            sc.name
                            }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="重定向URL">
                    <el-input v-model="clientInfo.redirect_uris"/>
                </el-form-item>
                <el-form-item label="code过期时间">
                    <el-input v-model="clientInfo.authorization_code_expires"/>
                </el-form-item>
                <el-form-item label="token过期时间">
                    <el-input v-model="clientInfo.access_token_expires"/>
                </el-form-item>
                <el-form-item label="刷新token时间">
                    <el-input v-model="clientInfo.refresh_token_expires"/>
                </el-form-item>
            </el-form>
            <template #footer>
      <span class="dialog-footer">
        <el-button @click="addOrUpdateInfo">提交</el-button>
        <el-button type="primary" @click="showModel = false">取消</el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import request from "/@/plugins/request.js";

const getClientPage = () => {
    request.get(`/admin/client?page=${currentPage.value}&size=${pageSize.value}`).then((res) => {
        clientList.value = res.data.data;
        totalPage.value = res.data.total;
    })
}

const getScopeTag = () => {
    request.get('/admin/scope/all').then((res) => {
        scopeTag.value = res.data.data;
    })
}

const addClientRequest = () => {
    // 需要将三个转换为数字
    clientInfo.authorization_code_expires = parseInt(clientInfo.authorization_code_expires.toString())
    clientInfo.access_token_expires = parseInt(clientInfo.access_token_expires.toString());
    clientInfo.refresh_token_expires = parseInt(clientInfo.refresh_token_expires.toString())
    request.post('/admin/client/add', clientInfo).then((res) => {
        ElMessage(res.data.msg);
        getClientPage()
    })
}

const deleteClientRequest = (cid) => {
    request.delete("/admin/client/" + cid).then((res) => {
        ElMessage(res.data.msg);
        getClientPage()
    })
}

const queryClientRequest = () => {
    request.get("/admin/client/" + query.value).then((res) => {
        clientList.value = res.data.data
    })
}

onMounted(() => {
    getClientPage()
    getScopeTag()
})

const clientInfo = reactive({
    client_id: "",
    client_secret: "***",
    client_name: "",
    authorization_grant_types: [],
    redirect_uris: "",
    scopes: [],
    authorization_code_expires: 100,
    access_token_expires: 100,
    refresh_token_expires: 100
})

// 固定的
const authorizationGrantTypes = ["authorization_code", "refresh_token", "client_credentials"]

const scopeTag = ref([])

const clientList = ref([{
    client_id: "txY5YIoVttAs",
    client_secret: "***",
    client_name: "21512",
    authorization_grant_types: ["authorization_code", "refresh_token"],
    redirect_uris: "http://www.baidu.com/login",
    scopes: ["userinfo"],
    authorization_code_expires: 100,
    access_token_expires: 100,
    refresh_token_expires: 100
}])

// 分页数量
const pageSize = ref(10)
// 分页
const totalPage = ref(1)  // 这个是后端的数据
const currentPage = ref(1)
const currentChange = (currentPages) => { // current-page 改变时触发
    currentPage.value = currentPages
}

// 模态框
const showModel = ref(false)

const showNewInfo = () => {   // 新增
    resetInfo()
    showModel.value = true
}
const showEditInfo = (rowClientInfo) => { // 修改
    clientInfo.client_id = rowClientInfo.client_id
    clientInfo.client_name = rowClientInfo.client_name
    clientInfo.client_secret = rowClientInfo.client_secret
    clientInfo.authorization_grant_types = rowClientInfo.authorization_grant_types
    clientInfo.scopes = rowClientInfo.scopes
    clientInfo.redirect_uris = rowClientInfo.redirect_uris
    clientInfo.authorization_code_expires = rowClientInfo.authorization_code_expires
    clientInfo.access_token_expires = rowClientInfo.access_token_expires
    clientInfo.refresh_token_expires = rowClientInfo.refresh_token_expires
    showModel.value = true
}

const resetInfo = () => {   // 需要清空
    clientInfo.client_id = ""
    clientInfo.client_name = ""
    clientInfo.client_secret = ""
    clientInfo.authorization_grant_types = []
    clientInfo.scopes = []
    clientInfo.redirect_uris = ""
    clientInfo.authorization_code_expires = 0
    clientInfo.access_token_expires = 0
    clientInfo.refresh_token_expires = 0
}

// crud
const addOrUpdateInfo = () => {
    const excludedFields = ["client_id", "authorization_grant_types", "scopes", "authorization_code_expires", "access_token_expires", "refresh_token_expires"];
    const isEmpty = Object.entries(clientInfo).every(([key, value]) => excludedFields.includes(key) || value === "" || (Array.isArray(value) && value.length === 0));
    if (isEmpty) {
        ElMessage("请填写必填项目");
    } else {
        addClientRequest()
        showModel.value = false
    }
}

const deleteInfo = (cid) => {
    ElMessageBox.confirm('是否删除用户' + cid, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteClientRequest(cid)
    }).catch(() => {
        // 取消删除操作
        ElMessage('取消')
    });
}

// 搜索
const query = ref()
const queryClient = () => {
    if (query.value === undefined || query.value === "") {
        getClientPage()
    } else {
        queryClientRequest()
    }
}
</script>
